﻿using CKS.Core.Framework;
using CKS.Models;
using CKS.PLC.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace CKS.AGV.Core.PlcActions.OP10
{
    /// <summary>
    /// L2
    /// 检查出料口的零件类型，匹配送料任务
    /// 实时采集出料类别
    /// </summary>
    public class MatchTaskAction : BasePlcAction
    {
        public MatchTaskAction(DecodeValue _value) : base(_value)
        {
        }

        /// <summary>
        /// 实时采集L2出口零件类别;
        /// 查询输送任务、零件类别相等的未下发任务、并且匹配状态是false
        /// </summary>
        public override void Execute()
        {
           
           var REQ = Value.Value.ToInt();
            if(REQ == 1)
            {

                var partType = Value.GetLinkData(1).ToInt();
                var partItem = AgvCache.AllPartInfo.Find(a => a.PartType == partType);
                if(partItem!=null)
                    EventBus.Op10Request(Value.Position.ActionId, $"L{Value.Position.ActionId}:{partItem.Name}");
                else
                    EventBus.Op10Request(Value.Position.ActionId, $"L{Value.Position.ActionId}:Null");
                var task = repoTasks.Select.Where(a => a.PartType == partType && a.MatchOut == false && (int)a.TaskStatus < 10)
               .OrderBy(a => a.Id).First();
                if (task != null)
                {
                    task.MatchOut = true;
                    repoTasks.Update(task);
                    //匹配结束
                }
            }
            else
            {
                EventBus.Op10Request(Value.Position.ActionId,$"L{Value.Position.ActionId}:--" );
            }
        
           
        }

        
    }
}
